<template>
  <div class="serviceDetail">
    <div class="form_box">
      <h3 class="title">服务详情</h3>
      <Form
        :model="detailForm"
        :label-width="100"
      >
        <Form-item
          label="服务名称"
        >
          <Input
            v-model="detailForm.serviceName" readonly
          />
        </Form-item>
        <Form-item
          label="分组"
        >
          <Input
            v-model="detailForm.groupName" readonly
          />
        </Form-item>
        <Form-item label="保护阈值">
          <Input
            v-model="detailForm.protectThreshold" readonly
          />
        </Form-item>
        <Form-item label="服务路由类型">
          <Input
            v-model="routerType" readonly
          />
        </Form-item>
        <Form-item label="元数据">
          <div class="code_wrap">
            <codeEditor :value="detailForm.content" :config="editorConfig" ref="codeEditor"></codeEditor>
          </div>
        </Form-item>
      </Form>
    </div>
    <div class="table_title">
      <h3 class="title">集群: </h3>
      <span style="margin-left: 10px;">{{colony}}</span>
    </div>
    <div class="metadata_filter">
      <Form :model="filterData" inline>
        <FormItem>
          <span>元数据过滤</span>
        </FormItem>
        <Form-item label="">
          <Input v-model="filterData.key" placeholder="key"  :class="{error: filterData.keyError}"/>
        </Form-item>
        <Form-item label="">
          <Input v-model="filterData.value" placeholder="value"  :class="{error: filterData.valueError}"/>
        </Form-item>
        <FormItem>
          <Button type="primary" @click="filterHandle" style="margin-right: 10px;">添加过滤</Button>
          <Button type="default" @click="resetFilter">清空</Button>
        </FormItem>
      </Form>
    </div>
    <div style="margin-left: 10px;">
      <tag
        v-for="(item, index) in tagList"
        :key="index"
        closable
        size="medium"
        @on-close="closeHandle(item)"
      >{{item.key}}:{{item.value}}</tag>
    </div>
    <InnerPageTable
      ref="configureListTable"
      :config="pageTableConfig"
    >
    </InnerPageTable>
  </div>
</template>

<script>
import codeEditor from '@/components/common/CodeEditor'
import API from "@/api/serviceList";
import { generatecolonyColumns } from './colomns'
export default {
  name: "serviceDetail",
  props: {
    row: {
      type: Object,
      default: () => ({})
    },
    namespaceId: {
      type: String,
      default: ""
    },
  },
  computed: {
    routerType() {
      // selector---selector.type != 'none', 显示selector.expression 否则显示selector.type
        return this.detailForm.selector.type !== 'none' ? this.detailForm.selector.expression : this.detailForm.selector.type
    }
  },
  components: {
    codeEditor
  },
  data() {
    return {
      detailForm: {
        protectThreshold: "",
        groupName: "",
        content: "",
        serviceName: "",
        selector: {}
      },
      hasDetailData: false,
      pageTableConfig: {
        loadDataFn: this.getTableList,
        columns: generatecolonyColumns.bind(this)(),
        autoFirst: false,
        allSelection: [],
        initParam: {
          namespaceId: this.row.namespaceId,
          clusterName: this.row.name,
          groupName: this.row.groupName,
          serviceName: this.row.name,
        }
      },
      editorConfig: {
        language: 'json',
        readOnly: true
      },
      colony: '',
      filterData: {
        key: '',
        value: '',
        keyError: '',
        valueError: ''
      },
      tagList: [],
      tableData: []
    };
  },
  mounted() {
    this.getDetail()
  },
  methods: {
    getDetail() {
      const param = {
        namespaceId: this.row.namespaceId,
        groupName: this.row.groupName,
        serviceName: this.row.name
      }
      API.getServiceDetail(param).then(res => {
        res.data.service.protectThreshold = String(res.data.service.protectThreshold);
        this.detailForm = res.data.service
        this.$refs.codeEditor.setValue(JSON.stringify(this.detailForm.metadata))
        this.colony = res.data.clusters[0].name
        this.pageTableConfig.initParam.clusterName = this.colony
        this.hasDetailData = true;
        this.$nextTick(() => {
          this.$refs.configureListTable.load(this.pageTableConfig.initParam)
        })
      })
    },
    filterHandle() {
      if (!this.filterData.value) {
        this.filterData.valueError = '请输入value'
      } else {
        this.filterData.valueError = ''
      }
      if (!this.filterData.key) {
        this.filterData.keyError = '请输入key'
      } else {
        this.filterData.keyError = ''
      }
      if (this.filterData.keyError || this.filterData.valueError) return
      const index = this.tagList.findIndex(m => m.key === this.filterData.key && m.value === this.filterData.value)
      if (index < 0) {
        this.tagList.push({
          key: this.filterData.key,
          value: this.filterData.value
        })
      }
      this.filterData.key = ''
      this.filterData.value = ''
      this.filterMetadata()
    },
    closeHandle(item) {
      const index = this.tagList.findIndex(m => m.key === item.key && m.value === item.value)
      this.tagList.splice(index, 1)
      if (this.tagList.length) {
        this.filterMetadata()
      } else {
        this.$refs.configureListTable.load(this.pageTableConfig.initParam)
      }
    },
    filterMetadata() {
      const filterDataObj = {}
      this.tagList.forEach(item => {
        filterDataObj[item.key] = item.value
      })
      const data = this.tableData.filter(item => {
        console.log('ssssssssss', JSON.stringify(filterDataObj), item.metadata)
        return JSON.stringify(filterDataObj) === item.metadata
      })
      this.$refs.configureListTable.tableData = data
    },
    resetFilter() {
      for(let key of Object.keys(this.filterData)) {
        this.filterData[key] = ''
      }
      this.tagList = []
      this.$refs.configureListTable.tableData = this.tableData
    },
    getTableList(tableObj) {
      const { responseProcess, initParam, param } = tableObj
      const params = {
        ...initParam,
        ...param
      }

      API.getInstance(params).then(res => {
        res.records.forEach(item => {
          item.metadata = JSON.stringify(item.metadata)
        })
        this.tableData = JSON.parse(JSON.stringify(res.records))
        responseProcess(res)
      })
    },
    async statusHandle(row) {
      const msgText = row.enabled ? '下线' : '上线'
      let confirm = false
      await new $confirm(`确认${msgText}？`, this).then(_ => confirm = true).catch(_ => confirm = false)
      if (!confirm) return
      const params = {
        serviceName: this.detailForm.serviceName,
        clusterName: row.clusterName,
        groupName: this.detailForm.groupName,
        ip: row.ip,
        port: row.port,
        ephemeral: row.ephemeral,
        weight: row.weight,
        enabled: !row.enabled,
        metadata: JSON.parse(row.metadata),
        namespaceId: this.namespaceId
      }
      API.changeInstance(params).then(res => {
        this.$message.success(msgText + '成功');
        row.enabled = !row.enabled
      })
    }
  }
};
</script>

<style scoped lang="less">
.serviceDetail{
  .form_box{
    width: 70%;
    //margin-left: auto;
    //margin-right: auto;
  }
  .code_wrap{
    height: 200px;
  }
  .title{
    margin-bottom: 20px;
    margin-top: 20px;
    padding-left: 30px;
    //width: 200px;
    //text-align: center;
  }
  .table_title{
    display: flex;
    align-items: center;
  }
  .metadata_filter{
    padding-left: 10px;
    display: flex;
    align-items: center;
    /deep/ .ivu-input-small{
      height: 30px;
    }
    /deep/ .error{
      .ivu-input-small{
        border-color: red !important;
      }
    }
  }
  .filter-form {
    /deep/.ivu-form-item {
      margin-bottom: 0
    }
  }
  /deep/.t-action-btn:hover {
    color: #ff8c6f;
  }

}

</style>
